#!/usr/bin/env python3
import os
import sys
import time
import json
import squashfs
import traceback
import PyQt5.QtCore as QtCore
import PyQt5.QtWidgets as QtWidgets

def UploadProgress(info):
    loadingText.setText(f"<p align='center'>正在加载应用程序“{info[0]}”（{info[1]}/{fileNumber}）</p>")
    loadingProgressbar.setValue(info[1])

class LoadingThread(QtCore.QThread):
    uploadProgress = QtCore.pyqtSignal(list)
    def __init__(self) -> None:
        super().__init__()

    def run(self):
        for i in fileList:
            try:
                s = squashfs.Squashfs()
                squashfsPath = f"{autoPath}/{i}"
                mountPath = f"/dclc-mount/rw/program-mount-{time.time()}"
                if not os.path.exists(mountPath):
                    os.system(f"pkexec mkdir -p '{mountPath}'")
                s.MountReadWriteAndNotSave(squashfsPath, mountPath)
                s.BuildLinkToRootPath(mountPath)
            except:
                traceback.print_exc()
                QtWidgets.QMessageBox.critical(window, "错误", traceback.format_exc())

def RunThread():
    global loadingThread
    loadingThread = LoadingThread()
    loadingThread.uploadProgress.connect(UploadProgress)
    loadingThread.start()

autoPath = "/"
fileList = os.listdir(autoPath)
fileNumber = len(fileList)
programPath = os.path.split(os.path.realpath(__file__))[0]  # 返回 string
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QMainWindow()
widget = QtWidgets.QWidget()
layout = QtWidgets.QGridLayout()
iconText = QtWidgets.QLabel(f"<p><img src='{programPath}/icon.svg' width=64>由 RacoonGX 团队制作</p>")
iconText.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignBottom)
loadingText = QtWidgets.QLabel(f"<p align='center'>正在加载应用程序（0/{fileNumber}）</p>")
loadingText.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignBottom)
loadingProgressbar = QtWidgets.QProgressBar()
loadingProgressbar.setMaximum(fileNumber)
layout.addWidget(iconText, 2, 0)
layout.addWidget(loadingText, 0, 0)
layout.addWidget(loadingProgressbar, 1, 0)
widget.setLayout(layout)
window.setCentralWidget(widget)
window.setLayout(layout)


screen = QtWidgets.QDesktopWidget().screenGeometry()
size = window.geometry()

window.setFixedSize(int(screen.width() / 2), size.height())
#size = window.geometry()
window.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
window.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
window.show()
print(size.height())
UploadProgress(["WPS Office", 1])
sys.exit(app.exec_())
